package com.example.safeassistan.train.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.train.adapter.DownLoadAdapter;
import com.example.safeassistan.train.model.DownLoad;
import com.example.safeassistan.train.util.MaterialUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/***
 * 我的下载记录
 * **/

public class Activity_Load extends BaseActivity implements View.OnClickListener {
    private boolean isSelectAll = false;
    private TextView _barTvRight;
    private RelativeLayout rlBottomBar;
    private DownLoadAdapter downLoadAdapter;
    private ImageView ivSelectAll;
    private RecyclerView rcView;
    private int tag = 1;//1-编辑，2-删除
    private TextView tvDelete;
    private SmartRefreshLayout refresh;

    /********/
    private String rootPath = Environment.getExternalStorageDirectory()+"/scorers/material/";
    private List<DownLoad.DataBean> datas;

    public void getFileDir(String filePath) {
        try{
            File f = new File(filePath);
            File[] files = f.listFiles();// 列出所有文件
            if(files != null){
                int count = files.length;// 文件个数
                datas.clear();
                for (int i = 0; i < count; i++) {
                    File file = files[i];
                    DownLoad.DataBean load=new DownLoad.DataBean();
                    load.setTitle(file.getName());
                    load.setPath(file.getPath());
                    String filetype=file.getName();
                    String [] str=null;
                    str=  filetype.split("\\.");
                    if(str.length>1){
                        load.setFileType(str[1]);
                    }
                    datas.add(load);
                }
            }
            refresh.finishRefresh();
            downLoadAdapter = new DownLoadAdapter(datas);
            rcView.setLayoutManager(new LinearLayoutManager(getContext()));
            rcView.setAdapter(downLoadAdapter);
            downLoadAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    switch (view.getId()){
                        case R.id.ivSelect:
                            Log.e("aaa",datas.get(position).isSelect()+"");
                            boolean isSelect = !datas.get(position).isSelect();
                            ImageView ivSelect = (ImageView) view;
                            MaterialUtil.checkItem(isSelect, ivSelect);
                            datas.get(position).setSelect(isSelect);
                            w:
                            for (int i = 0; i < datas.size(); i++) {
                                DownLoad.DataBean validBean = datas.get(i);
                                boolean isItemSelect = validBean.isSelect();
                                if (isItemSelect) {
                                    isSelectAll = true;
                                } else {
                                    isSelectAll = false;
                                    break w;//根据标记，跳出嵌套循环
                                }
                            }
                            MaterialUtil.checkItem(isSelectAll, ivSelectAll);
                            break;
                    }
                }
            });
            downLoadAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    //点击打开资料云库
                    openAndroidFile(datas.get(position).getPath());
                    //Activity_Material_DownloadDetail.actionStart(getContext(),datas.get(position).getPath());
                }
            });
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context,Activity_Load.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id._barTvRight:
                if (tag == 1) {//1-结算，2-删除等操作
                    tag = 2;
                } else {
                    tag = 1;
                }
                setState();
                break;
            case R.id.ivSelectAll:
                //全选/取消全选
                MaterialUtil.selectAll(datas, isSelectAll);
                isSelectAll = !isSelectAll;
                MaterialUtil.checkItem(isSelectAll, ivSelectAll);
                downLoadAdapter.notifyDataSetChanged();
                break;
            case R.id.tvDelete:
                //删除地址
                deleteFolderFile(MaterialUtil.getSelectGoodsIds(datas));
                downLoadAdapter.notifyDataSetChanged();
                break;
        }
    }

    public void deleteFolderFile(List<String> dedeletePaths){
        try {
            for (int i = 0; i < dedeletePaths.size(); i++) {
                    File photoFile = new File(dedeletePaths.get(i));
                    photoFile.delete();
                    if(new File(dedeletePaths.get(dedeletePaths.size()-1)).delete()){
                        refresh.autoRefresh();
                        rlBottomBar.setVisibility(View.GONE);
                    }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private static final String[][] MIME_MapTable={
            //{后缀名，    MIME类型}
            {".3gp",    "video/3gpp"},
            {".apk",    "application/vnd.android.package-archive"},
            {".asf",    "video/x-ms-asf"},
            {".avi",    "video/x-msvideo"},
            {".bin",    "application/octet-stream"},
            {".bmp",      "image/bmp"},
            {".c",        "text/plain"},
            {".class",    "application/octet-stream"},
            {".conf",    "text/plain"},
            {".cpp",    "text/plain"},
            {".doc",    "application/msword"},
            {".docx",    "application/msword"},
            {".exe",    "application/octet-stream"},
            {".gif",    "image/gif"},
            {".gtar",    "application/x-gtar"},
            {".gz",        "application/x-gzip"},
            {".h",        "text/plain"},
            {".htm",    "text/html"},
            {".html",    "text/html"},
            {".jar",    "application/java-archive"},
            {".java",    "text/plain"},
            {".jpeg",    "image/jpeg"},
            {".JPEG",    "image/jpeg"},
            {".jpg",    "image/jpeg"},
            {".js",        "application/x-javascript"},
            {".log",    "text/plain"},
            {".m3u",    "audio/x-mpegurl"},
            {".m4a",    "audio/mp4a-latm"},
            {".m4b",    "audio/mp4a-latm"},
            {".m4p",    "audio/mp4a-latm"},
            {".m4u",    "video/vnd.mpegurl"},
            {".m4v",    "video/x-m4v"},
            {".mov",    "video/quicktime"},
            {".mp2",    "audio/x-mpeg"},
            {".mp3",    "audio/x-mpeg"},
            {".mp4",    "video/mp4"},
            {".mpc",    "application/vnd.mpohun.certificate"},
            {".mpe",    "video/mpeg"},
            {".mpeg",    "video/mpeg"},
            {".mpg",    "video/mpeg"},
            {".mpg4",    "video/mp4"},
            {".mpga",    "audio/mpeg"},
            {".msg",    "application/vnd.ms-outlook"},
            {".ogg",    "audio/ogg"},
            {".pdf",    "application/pdf"},
            {".png",    "image/png"},
            {".pps",    "application/vnd.ms-powerpoint"},
            {".ppt",    "application/vnd.ms-powerpoint"},
            {".pptx",    "application/vnd.ms-powerpoint"},
            {".prop",    "text/plain"},
            {".rar",    "application/x-rar-compressed"},
            {".rc",        "text/plain"},
            {".rmvb",    "audio/x-pn-realaudio"},
            {".rtf",    "application/rtf"},
            {".sh",        "text/plain"},
            {".tar",    "application/x-tar"},
            {".tgz",    "application/x-compressed"},
            {".txt",    "text/plain"},
            {".wav",    "audio/x-wav"},
            {".wma",    "audio/x-ms-wma"},
            {".wmv",    "audio/x-ms-wmv"},
            {".wps",    "application/vnd.ms-works"},
            //{".xml",    "text/xml"},
            {".xml",    "text/plain"},
            {".z",        "application/x-compress"},
            {".zip",    "application/zip"},
            {"",        "*/*"}
    };

    private static String getMIMEType(File file) {

        String type="*/*";
        String fName = file.getName();
        //获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if(dotIndex < 0)
            return type;
        /* 获取文件的后缀名 */
        String fileType = fName.substring(dotIndex,fName.length()).toLowerCase();
        if(fileType == null || "".equals(fileType))
            return type;
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for(int i=0;i<MIME_MapTable.length;i++){
            if(fileType.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }


    public void openAndroidFile(String filepath){
        Intent intent = new Intent();
        // 这是比较流氓的方法，绕过7.0的文件权限检查
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

        File file = new File(filepath);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//设置标记
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setAction(Intent.ACTION_VIEW);//动作，查看
        intent.setDataAndType(Uri.fromFile(file),getMIMEType(file));//设置类型
        startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_download;
    }

    @Override
    protected void initView() {
        setTitleText("我的下载");
        _barTvRight=findViewById(R.id._barTvRight);
        _barTvRight.setTextColor(getResources().getColor(R.color.gray3));
        _barTvRight.setText("编辑");
        _barTvRight.setVisibility(View.VISIBLE);
        _barTvRight.setOnClickListener(this);
        rlBottomBar=findViewById(R.id.rlBottomBar);
        tvDelete=findViewById(R.id.tvDelete);
        tvDelete.setOnClickListener(this::onClick);
        ivSelectAll=findViewById(R.id.ivSelectAll);
        ivSelectAll.setOnClickListener(this::onClick);
        refresh=findViewById(R.id.refresh);
        refresh.setEnableLoadMore(false);
        refresh.setEnableNestedScroll(true);
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                      getFileDir(rootPath);
                    }
                }, 1000);
            }
        });
        rcView=findViewById(R.id.rcView);
        refresh.autoRefresh();
        datas=new ArrayList<>();
    }


    private void setState() {
        switch (tag) {
            case 1:
                MaterialUtil.setVisibility(datas,false);
                _barTvRight.setText("编辑");
                rlBottomBar.setVisibility(View.GONE);
                downLoadAdapter.notifyDataSetChanged();
                break;
            case 2:
                MaterialUtil.setVisibility(datas,true);
                _barTvRight.setText("完成");
                rlBottomBar.setVisibility(View.VISIBLE);
                downLoadAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getTitleBarType() {
        return TITLEBAR_DEFAULT;
    }
}
